package com.zghhost.codedemo.weight;
 
public class WGRandom {
 
 
/**
 * 
 * @author wangguan
 * java 加权随机数
 */
public static void main(String[] args) {
		int a = 0;
		int b = 0;
		int c = 0;
		int d =0;
		int e = 0;
		int f = 0;
		
		int i = 10;
		for (int j = 0; j < 10000000; j++) {
			switch (i = doRamdon()) {
			case 0:
				a++;
				break;
			case 1:
				b++;
				break;
			case 2:
				c++;
				break;
			case 3:
				d++;
				break;
			case 4:
				e++;
				break;
			case 5:
				f++;
				break;
			
				
			default:
				System.out.println(">>>>>>>>>>>>" + i);
				break;
			}
		}
		
		System.out.println("a : " + a + "     b : " + b + "     c ：" + c+ "     d ：" + d+ "    e ：" + e+ "    f  ：" + f);
		System.out.println(a+b+c+d+e+f);
		
	}
 
	private static int doRamdon() {
		double[] ds = new double[] {1.0 , 50.0 , 4.0 , 15.0 , 70.0 , 20.0  };
		double sum = getSum(ds);
		double last = 0;
		for (int i = 0; i < ds.length; i++) {
			sum = sum- last;
			double random = Math.random();
			if (random <= ds[i] / sum) {
				return i;
			}
			last = ds[i];
		}
		
		return 5;
	}
 
	private static double getSum(double[] weight) {
		double sum = 0;
		for (double d : weight) {
			sum += d;
		}
		return sum;
	}
 
}